package com.nuc.workflowserver.controller;

import com.nuc.workflowserver.common.model.ResultModel;
import com.nuc.workflowserver.model.pojo.User;
import com.nuc.workflowserver.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("login")
@Api(value = "登录接口", description = "登录校验")
public class LoginController {

    @Autowired
    IUserService iUserService;

    @GetMapping("/isLogin")
    @ApiOperation("登录校验")
    public ResultModel isLogin(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (null != user) {
            return new ResultModel(user, true);
        }
        return new ResultModel("请先登录！", false);
    }

    @PostMapping("/login")
    @ApiOperation("登录")
    public ResultModel login(@RequestBody User user, HttpSession session) {
        if (null != user && user.getUserName() != ""
                && user.getPassword() != "") {
            User userDB = iUserService.selectByPrimary(user);
            if (null == userDB) {
                return new ResultModel("账号或密码错误！", false);
            } else {
                //将登录对象放入session中
                session.setAttribute("user", userDB);
                return new ResultModel("登录成功！", true);
            }
        }
        return new ResultModel("请求错误，请联系管理员！", false);
    }

    @GetMapping("logout")
    @ApiOperation("退出登录")
    public ResultModel logout(HttpSession session) {
        session.invalidate();
        return new ResultModel("退出成功！", true);
    }

}
